import type { EqualResField, NumberResField } from "../../res/ResponseOption.js";
import { hex } from "../../util.js";

export const enum ResOp {
    Close = 0,
    Launch,
    LoadAsset,
    VarChange,
    IndexRegisterChange,
    StatusRegisterChange,
}

const OP_STRING: { [k in ResOp]: string } = {
    [ResOp.Close]: "关闭连接",
    [ResOp.Launch]: "启动信息",
    [ResOp.LoadAsset]: "加载资源",
    [ResOp.VarChange]: "图元变量变化通知",
    [ResOp.IndexRegisterChange]: "索引寄存器变化通知",
    [ResOp.StatusRegisterChange]: "状态寄存器变化通知",
};

function op(op: ResOp): EqualResField {
    return {
        name: "功能码",
        kind: "equal",
        data: [op & 0xff, (op >> 8) & 0xff],
        value: `${hex(op & 0xff)} ${hex((op >> 8) & 0xff)} (${OP_STRING[op]})`,
    };
}

const crc: EqualResField = {
    name: "crc",
    kind: "equal",
    data: [0x34],
    value: "0x34",
};

// const length: CustomResField = {
//     name: "长度",
//     desc: "见通用请求头的长度字段",
//     kind: "custom",
//     matcher: function (data) {
//         let len = data.at(0);
//         data.consume(1);
//         if (len < 255) {
//             if (data.length !== len) {
//                 return null;
//             }
//             return "" + len;
//         }

//         len = data.u16le(0);
//         data.consume(2);
//         if (len < 0xffff) {
//             if (data.length !== len) {
//                 return null;
//             }
//             return "" + len;
//         }

//         len = data.u32le(0);
//         data.consume(4);
//         if (data.length !== len) {
//             return null;
//         }
//         return "" + len;
//     },
// };

const length: NumberResField = {
    name: "长度",
    kind: "u16",
};

export const fields = {
    op,
    crc,
    length,
};
